package com.kangdi.riggie.filter;

import com.alibaba.fastjson.JSON;
import com.kangdi.riggie.common.BaseContext;
import com.kangdi.riggie.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
@WebFilter(filterName = "LoginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter  {
    private static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();//匹配请求路径是否在不需要拦截的地址中
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;
        String[] urls=new String[]{
          "/employee/login",
          "/employee/logout",
          "/backend/**",
          "/front/**",
                "/user/sendMsg",
                "/user/login",
        };
        String path = request.getServletPath();
        log.info("拦截到的请求为"+path);
        boolean cheak = cheak(urls, path);
        if (cheak){
            log.info("此请求不需要处理");
            filterChain.doFilter(request,response);
            return;
        }
        if (request.getSession().getAttribute("employee")!=null){
            log.info("该用户已登录");
            BaseContext.add((Long) request.getSession().getAttribute("employee"));
            filterChain.doFilter(request,response);
            return;
        }
        if (request.getSession().getAttribute("user")!=null){
            log.info("该用户已登录");
            BaseContext.add((Long) request.getSession().getAttribute("user"));
            filterChain.doFilter(request,response);
            return;
        }
        log.info("跳转到登录界面");
        response.getWriter().write(JSON.toJSONString(Result.error("NOTLOGIN")));

    }
    //匹配请求路径是否在不需要拦截的地址中
    public boolean cheak(String[] urls,String path){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, path);
            if (match){
                return true;
            }
        }
        return false;
    }
}
